package com.wosai.teach.activity;

import java.lang.ref.WeakReference;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.LayoutParams;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;
import com.wosai.teach.R;
import com.wosai.teach.cst.C;
import com.wosai.teach.dto.JsonResult;
import com.wosai.teach.entity.Details;
import com.wosai.teach.entity.MicroClass;
import com.wosai.teach.entity.Recommend;
import com.wosai.teach.utils.OtherUtils;

public class MicroClassActivity extends AppFragmentActivity {
	/**
	 * 用于开始和暂停的按钮
	 */
	private Button bt;
	/**
	 * 绘图容器对象，用于把视频显示在屏幕上
	 */
	private SurfaceView pView;
	/**
	 * 视频播放地址
	 */
	private String url;
	/**
	 * 播放器控件
	 */
	private MediaPlayer mediaPlayer;
	/**
	 * 保存义播视频大小
	 */
	private int postSize;
	/**
	 * 进度条控件
	 */
	private SeekBar seekbar;
	/**
	 * 用于判断视频是否在播放中
	 */
	private boolean flag = true;
	private RelativeLayout rl;
	/**
	 * 用于是否显示其他按钮
	 */
	private boolean display;
	/**
	 * 用于判断是否全屏
	 */
	private boolean fullScreen = false;
	/**
	 * ProgressBar
	 */
	private View view;
	/**
	 * 更新进度条用
	 */
	private upDateSeekBar update;
	/**
	 * 用于响应2次点击屏幕事件
	 */
	private long exitTime = 0;
	private CountTimeThread mCountTimeThread;
	/**
	 * 分类
	 */
	private String type = "0";

	private TabHost mTabhost;
	// 详情介绍标签
	public static final String TAB_DETAILS = "DetailsTab";
	// 相关推荐标签
	public static final String TAB_RECOMMEND = "RecommendTab";

	@SuppressLint("SdCardPath")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		try {
			setContentView(R.layout.activity_microclass); // 加载布局文件
		} catch (Exception e) {
			e.printStackTrace();
		}

		setmPageName("微课堂");
		setTopTitle(R.string.micro_class);
		enableBack(true);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 应用运行时，保持屏幕高亮，不锁屏
		init();

		setListener(); // 绑定相关事件

		startCountTimeThread();

	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	/**
	 * 初始化数据
	 */
	private void init() {
		mediaPlayer = new MediaPlayer(); // 创建一个播放器对象
		update = new upDateSeekBar(); // 创建更新进度条对象

		seekbar = (SeekBar) findViewById(R.id.seekbar); // 进度条
		bt = (Button) findViewById(R.id.play);
		bt.setEnabled(false); // 刚进来，设置其不可点击
		pView = (SurfaceView) findViewById(R.id.mSurfaceView);
		pView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // 不缓冲
		pView.getHolder().setKeepScreenOn(true); // 保持屏幕高亮
		try {
			SurFaceViewCallback callback = new SurFaceViewCallback();
			SurfaceHolder sur = pView.getHolder();
			sur.addCallback(callback); // 设置监听事件
		} catch (Exception e) {
			e.printStackTrace();
		}

		rl = (RelativeLayout) findViewById(R.id.rl2);
		view = findViewById(R.id.pb);

		Intent it = getIntent();
		type = it.getStringExtra("type");
		type = type == null ? "0" : type;

		View tab1 = (View) LayoutInflater.from(this).inflate(
				R.layout.activitiy_microclass_tabmini, null);
		TextView text1 = (TextView) tab1.findViewById(R.id.tab_label);
		text1.setText("详情介绍");

		View tab2 = (View) LayoutInflater.from(this).inflate(
				R.layout.activitiy_microclass_tabmini, null);
		TextView text2 = (TextView) tab2.findViewById(R.id.tab_label);
		text2.setText("相关推荐");

		mTabhost = (TabHost) findViewById(R.id.tabhost);
		mTabhost.setup();

		// 详情介绍
		mTabhost.addTab(mTabhost.newTabSpec("tab1").setIndicator(tab1)
				.setContent(R.id.tab1));

		// 相关推荐
		mTabhost.addTab(mTabhost.newTabSpec("tab2").setIndicator(tab2)
				.setContent(R.id.tab2));

		if ("0".equals(type)) {
			mTabhost.setCurrentTab(0);
		} else {
			mTabhost.setCurrentTab(1);
		}
		url = "http://teach-platform.oss-cn-hangzhou.aliyuncs.com/experiment/weiketang/VID_20150822_114040.mp4 ";

		getAll();
	}

	/**
	 * 获取全部数据
	 */
	private void getAll() {
		String url = C.HTTP_URL_MICROCLASS;
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.GET, url,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						System.out.println("onSuccess" + responseInfo.result);
						JsonResult result = OtherUtils
								.genJsonResult(responseInfo);
						if (result != null && result.getResult() == 0) {
							JsonResult jr = JSON.parseObject(
									responseInfo.result, JsonResult.class);
							List<MicroClass> microClassList = JSON
									.parseArray(jr.getObject().toString(),
											MicroClass.class);
							db.deleteAll(Selector.from(MicroClass.class));
							db.deleteAll(Selector.from(Recommend.class));
							db.saveAll(microClassList);
							for (MicroClass mic : microClassList) {
								Recommend rec = new Recommend();
								rec.setId(mic.getId());
								rec.setUpdateDate(mic.getUpdateDate());
								rec.setName(mic.getName());
								rec.setMicrocourseTypeId(mic
										.getMicrocourseTypeId());
								rec.setPlayTimes(mic.getPlayTimes());
								db.save(rec);
								
								Details det = new Details();
								
							}

						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						System.out.println("onFailure" + msg);
					}
				});

	}

	/**
	 * 开始启动线程控制按钮组件的显示.
	 */
	private void startCountTimeThread() {
		mCountTimeThread = new CountTimeThread(3);
		mCountTimeThread.start();
	}

	class PlayMovie extends Thread { // 播放视频的线程

		int post = 0;

		public PlayMovie(int post) {
			this.post = post;

		}

		@Override
		public void run() {
			Message message = Message.obtain();
			try {
				Log.i("hck", "runrun  " + url);
				mediaPlayer.reset(); // 回复播放器默认
				mediaPlayer.setDataSource(url); // 设置播放路径
				mediaPlayer.setDisplay(pView.getHolder()); // 把视频显示在SurfaceView上
				mediaPlayer.setOnPreparedListener(new Ok(post)); // 设置监听事件
				mediaPlayer.prepare(); // 准备播放
			} catch (Exception e) {
				message.what = 2;
				Log.e("hck", e.toString());
			}

			super.run();
		}
	}

	class Ok implements OnPreparedListener {
		int postSize;

		public Ok(int postSize) {
			this.postSize = postSize;
		}

		@Override
		public void onPrepared(MediaPlayer mp) {
			view.setVisibility(View.GONE); // 准备完成后，隐藏控件
			bt.setVisibility(View.GONE);
			rl.setVisibility(View.GONE);
			bt.setEnabled(true);
			display = false;
			if (mediaPlayer != null) {
				mediaPlayer.start(); // 开始播放视频
			} else {
				return;
			}
			if (postSize > 0) { // 说明中途停止过（activity调用过pase方法，不是用户点击停止按钮），跳到停止时候位置开始播放
				mediaPlayer.seekTo(postSize); // 跳到postSize大小位置处进行播放
			}
			new Thread(update).start(); // 启动线程，更新进度条
		}
	}

	/**
	 * 监听事件
	 */
	private class SurFaceViewCallback implements Callback { // 上面绑定的监听的事件

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			System.out.println("||holder||" + holder);
			System.out.println("||format||" + format);
			System.out.println("||width||" + width);
			System.out.println("||height||" + height);

		}

		@Override
		public void surfaceCreated(SurfaceHolder holder) { // 创建完成后调用
			if (postSize > 0 && url != null) { // 说明，停止过activity调用过pase方法，跳到停止位置播放
				new PlayMovie(postSize).start();
				flag = true;
				int sMax = seekbar.getMax();
				int mMax = mediaPlayer.getDuration();
				seekbar.setProgress(postSize * sMax / mMax);
				postSize = 0;
				view.setVisibility(View.GONE);
			} else {
				new PlayMovie(0).start(); // 表明是第一次开始播放
			}
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) { // activity调用过pase方法，保存当前播放位置
			if (mediaPlayer != null && mediaPlayer.isPlaying()) {
				postSize = mediaPlayer.getCurrentPosition();
				mediaPlayer.stop();
				flag = false;
				view.setVisibility(View.VISIBLE);
			}
		}
	}

	private void setListener() {
		mediaPlayer
				.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
					@Override
					public void onBufferingUpdate(MediaPlayer mp, int percent) {
					}
				});

		mediaPlayer
				.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { // 视频播放完成
					@Override
					public void onCompletion(MediaPlayer mp) {
						flag = false;
						bt.setBackgroundResource(R.drawable.movie_play_bt);
					}
				});

		mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
			@Override
			public void onPrepared(MediaPlayer mp) {

			}
		});
		/**
		 * 如果视频在播放，则调用mediaPlayer.pause();，停止播放视频，反之，mediaPlayer.start()
		 * ，同时换按钮背景
		 */
		bt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mediaPlayer.isPlaying()) {
					bt.setBackgroundResource(R.drawable.movie_play_bt);
					mediaPlayer.pause();
					postSize = mediaPlayer.getCurrentPosition();
				} else {
					if (flag == false) {
						flag = true;
						new Thread(update).start();
					}
					mediaPlayer.start();
					bt.setBackgroundResource(R.drawable.movie_stop_bt);

				}
			}
		});
		seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {

				int value = seekbar.getProgress() * mediaPlayer.getDuration() // 计算进度条需要前进的位置数据大小
						/ seekbar.getMax();
				mediaPlayer.seekTo(value);

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {

			}
		});
		/**
		 * 点击屏幕，切换控件的显示，显示则应藏，隐藏，则显示
		 */
		final ViewGroup.LayoutParams lp = pView.getLayoutParams();
		final int height = lp.height;
		pView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				mCountTimeThread.reset();

				display = (bt.getVisibility() == View.VISIBLE);
				if (!display) {
					// 当有按下事件时,如果控件不可见,则使其可见.
					rl.setVisibility(View.VISIBLE);
					bt.setVisibility(View.VISIBLE);
					pView.setVisibility(View.VISIBLE);
					display = true;
				}

				WindowManager.LayoutParams attrs = getWindow().getAttributes();
				if ((System.currentTimeMillis() - exitTime) > 1000) {
					Toast.makeText(MicroClassActivity.this, "再按一次切换全屏",
							Toast.LENGTH_SHORT).show();
					MobclickAgent.onKillProcess(MicroClassActivity.this);
					exitTime = System.currentTimeMillis();
				} else {
					if (fullScreen) {
						/**
						 * 设置退出全屏
						 */
						lp.height = height;
						lp.width = LayoutParams.MATCH_PARENT;
						pView.setLayoutParams(lp);
						fullScreen = false;

						setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 设置竖屏

						attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
						getWindow().setAttributes(attrs);
						getWindow()
								.clearFlags(
										WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
						enableShowHeadTop(true);

					} else {

						setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 设置横屏

						/**
						 * 设置播放为全屏
						 */
						lp.height = LayoutParams.MATCH_PARENT;
						lp.width = LayoutParams.MATCH_PARENT;
						pView.setLayoutParams(lp);
						fullScreen = true;

						// 隐藏顶部状态栏
						attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
						getWindow().setAttributes(attrs);
						getWindow()
								.addFlags(
										WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
						enableShowHeadTop(false);

					}
				}
			}
		});

	}

	/**
	 * 更新进度条
	 */
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (mediaPlayer == null) {
				flag = false;
			} else if (mediaPlayer.isPlaying()) {
				flag = true;
				int position = mediaPlayer.getCurrentPosition();
				int mMax = mediaPlayer.getDuration();
				int sMax = seekbar.getMax();
				seekbar.setProgress(position * sMax / mMax);
			} else {
				return;
			}
		};
	};

	class upDateSeekBar implements Runnable {

		@Override
		public void run() {
			mHandler.sendMessage(Message.obtain());
			if (flag) {
				mHandler.postDelayed(update, 1000);
			}
		}
	}

	/**
	 * activity销毁后，释放资源
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
		}
		System.gc();
	}

	/**
	 * 隐藏控制按钮的控件
	 */
	private void hide() {
		if (bt.getVisibility() == View.VISIBLE
				&& rl.getVisibility() == View.VISIBLE) {
			bt.setVisibility(View.GONE);
			rl.setVisibility(View.GONE);
		}
	}

	/**
	 * 如果mControllButtonLayout可见, 则无操作second秒之后隐藏mControllButtonLayout.
	 */
	private class CountTimeThread extends Thread {
		private final long maxVisibleTime;
		private long startVisibleTime;

		/**
		 * @param second
		 *            设置按钮控件最大可见时间,单位是秒
		 */
		public CountTimeThread(int second) {
			// 将时间换算成毫秒
			maxVisibleTime = second * 1000;

			// 设置为后台线程.
			setDaemon(true);
		}

		private MainHandler mHandler = new MainHandler(MicroClassActivity.this);

		private class MainHandler extends Handler {
			/** 隐藏按钮消息id */
			private final int MSG_HIDE = 0x0001;

			private WeakReference<MicroClassActivity> weakRef;

			public MainHandler(MicroClassActivity microClassActivity) {
				weakRef = new WeakReference<MicroClassActivity>(
						microClassActivity);
			}

			@Override
			public void handleMessage(Message msg) {
				final MicroClassActivity microClassActivity = weakRef.get();
				if (microClassActivity != null) {
					switch (msg.what) {
					case MSG_HIDE:
						microClassActivity.hide();
						break;
					}
				}

				super.handleMessage(msg);
			}

			public void sendHideControllMessage() {
				obtainMessage(MSG_HIDE).sendToTarget();
			}
		};

		/**
		 * 每当界面有操作时就需要重置mControllButtonLayout开始显示的时间,
		 */
		public synchronized void reset() {
			startVisibleTime = System.currentTimeMillis();
		}

		public void run() {
			startVisibleTime = System.currentTimeMillis();
			while (true) {
				// 如果已经到达了最大显示时间, 则隐藏功能控件.
				if ((startVisibleTime + maxVisibleTime) < System
						.currentTimeMillis()) {
					// 发送隐藏按钮控件消息.
					mHandler.sendHideControllMessage();
					startVisibleTime = System.currentTimeMillis();
				}
				try {
					// 线程休眠1s.
					Thread.sleep(1000);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
	}

}